<!--
对在进行生产时的生产单中的物料执行出库操作页
（这个行为理解成为生产单备料或供料更为合理一点。）
创建好并进入排班生产的订单表示可以开始生产了，这时就需要从仓库中取出物料来生产。但在客户那边的说法却叫做物料出库，有点歧义。
-->
<template>
  <a-modal
    :title="title"
    :width="1200"
    :maskClosable="false"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel">
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">

            <a-col :md="8" :sm="24" v-if="false">
              <a-form-item label="订单ID">
                <a-input v-model="queryParam.orderId" placeholder="请输入订单ID"/>
              </a-form-item>
            </a-col>

          </a-row>
        </a-form>
      </div>

      <div class="table-operator" v-show="materialType == $businessEnum.MATERIAL_TYPE_ENUM.packing.id && !readonly">
        <a-button type="primary" @click="$refs.addForm.add(emsOrder, materialType)" icon="plus">新增</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        :columns="dynamicColumn"
        :data="loadData"
        :alert="true"
        :showPagination="false">

        <template slot="normalNumber" slot-scope="text, record">
          <a-input-number v-model:value="record.normalNumber"
                          :min="0" :max="record.number-record.completedNumber<0?0:record.number-record.completedNumber"
                          style="width: 67px;"
                          :disabled="record.completedNumber>=record.number"/>
        </template>

        <template slot="extraNumber" slot-scope="text, record">
          <a-input-number v-model:value="record.extraNumber"
                          :min="0"
                          style="width: 67px;"
                          :disabled="record.completedNumber<record.number"/>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="$refs.outTimelineForm.show(record)">出库记录(包材未优化)</a>
        </span>
      </s-table>

      <add-form ref="addForm" @ok="handleOk"/>
      <out-timeline-form ref="outTimelineForm"/>
    </a-card>
  </a-modal>
</template>

<script>
import {STable} from '@/components'
import {page, del, add, listResult} from '@/api/modular/main/emsordermaterial/emsOrderMaterialManage'
import {addOutOrderForProductionOrder} from '@/api/modular/main/emsorder/emsOrderManage'
import addForm from '@/views/main/emsordermaterial/emsOrderMaterialAddFormOutOrder'
import editForm from '@/views/main/emsordermaterial/emsOrderMaterialEditForm'
import outTimelineForm from '@/views/main/emsordermaterial/emsOrderMaterialOutTimelineForm'
import materialForm from '@/views/main/emsmaterial/emsMaterialIndex'
import emsMaterialIndex1 from '@/views/main/emsmaterial/emsMaterialIndex1'
import productAddForm from '@/views/main/emsorder/emsOrderProductAddForm'
import productEditForm from '@/views/main/emsorder/emsOrderProductEditForm'

export default {
  components: {
    STable,
    addForm,
    editForm,
    materialForm,
    emsMaterialIndex1,
    productAddForm,
    productEditForm,
    outTimelineForm,
  },
  props: {
    readonly: false,
  },
  data() {
    return {
      title: null,
      advanced: false, // 高级搜索 展开/关闭
      queryParam: {},  // 查询参数
      viewState: '',
      viewStateEnum: {
        materialOut: 'materialOut',
        packingOut: 'packingOut',
      },
      extra: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return page(Object.assign(parameter, this.queryParam)).then((res) => {
          res.data.rows.forEach(value => {
            value.normalNumber = 0
          })
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      replaceFields: {
        key: 'id',
      },
      visible: false,
      confirmLoading: false,
      emsOrder: null,
      materialType: null
    }
  },
  watch: {
    emsOrder() {
      let _this = this
      setTimeout(function () {
        _this.$refs.table.refresh()
      }, 100)
    }
  },
  computed: {
    dynamicColumn() {
      switch (this.viewState) {
        case this.viewStateEnum.materialOut:
          return [
            {
              title: '物料',
              dataIndex: 'materialName'
            },
            {
              title: '物料编码',
              dataIndex: 'materialCode'
            },
            {
              title: '产品',
              dataIndex: 'productName',
            },
            {
              title: 'BOM',
              dataIndex: 'bomName',
              customRender: (text, record, index) => `${record.bomCode}(${record.bomName})`,
              ellipsis: false,
            },
            {
              title: '总数量',
              dataIndex: 'number'
            },
            {
              title: '已出库数量',
              dataIndex: 'completedNumber'
            },
            {
              title: '正常出库数量',
              dataIndex: 'normalNumber',
              scopedSlots: {customRender: 'normalNumber'}
            },
            {
              title: '额外出库数量',
              dataIndex: 'extraNumber',
              scopedSlots: {customRender: 'extraNumber'}
            }
          ]
        case this.viewStateEnum.packingOut:
          return [
            {
              title: '序号', width:'80px',
              dataIndex: '',
              customRender: (text, record, index) => `${index + 1}`
            },
            {
              title: '包材编号',
              dataIndex: 'materialCode'
            },
            {
              title: '包材名称',
              dataIndex: 'materialName',
            },
            {
              title: '需求数量',
              dataIndex: 'number'
            },
            {
              title: '已出库数量',
              dataIndex: 'completedNumber'
            },
            {
              title: '待出库数量',
              dataIndex: '',
              customRender: (text, record, index) => `${record.number - record.completedNumber}`
            },
            {
              title: '本次出库数量',
              dataIndex: 'normalNumber',
              scopedSlots: {customRender: 'normalNumber'}
            },
            {
              title: '操作',
              dataIndex: 'action',
              width: '150px',
              scopedSlots: {customRender: 'action'}
            }
          ]
        case 'packingOutReadonly':  //TODO 这个ViewState是在哪里出现的？在UI中得找找
          return [
            {
              title: '序号', width:'80px',
              dataIndex: '',
              customRender: (text, record, index) => `${index + 1}`
            },
            {
              title: '包材编号',
              dataIndex: 'materialCode'
            },
            {
              title: '包材名称',
              dataIndex: 'materialName',
            },
            {
              title: '需求数量',
              dataIndex: 'number'
            },
            {
              title: '已出库数量',
              dataIndex: 'completedNumber'
            },
            {
              title: '待出库数量',
              dataIndex: '',
              customRender: (text, record, index) => `${record.number - record.completedNumber}`
            },
            {
              title: '操作',
              dataIndex: 'action',
              width: '150px',
              scopedSlots: {customRender: 'action'}
            }
          ]
        default:
          return []
      }
    },
  },
  methods: {
    show(record, title, viewState, extra) {
      this.visible = true
      this.emsOrder = record
      this.title = '出库'
      // this.viewState = viewState
      this.extra = extra
      if (extra) {
        this.viewState = extra.viewState || this.viewState
        this.materialType = extra.materialType
        if (extra.materialType == this.$businessEnum.MATERIAL_TYPE_ENUM.material.id
          || extra.materialType == this.$businessEnum.MATERIAL_TYPE_ENUM.product.id
          || extra.materialType == this.$businessEnum.MATERIAL_TYPE_ENUM.cable.id) {
          this.viewState = this.viewStateEnum.materialOut
        } else if (extra.materialType == this.$businessEnum.MATERIAL_TYPE_ENUM.packing.id) {
          this.viewState = this.viewStateEnum.packingOut
        }
      }

      this.queryParam.materialType = extra.materialType
      this.queryParam.orderId = record.orderId
      this.queryParam.pageSize = -1

      setTimeout(() => {
        this.handleOk()
      }, 100)
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleSubmit() {
      let emsOrder = this.emsOrder
      let $data = this.$refs.table.$data
      $data = $data.localDataSource

      let filterData = $data.filter(value => value.normalNumber > 0 || value.extraNumber > 0)
      if (filterData.length == 0) {
        this.$message.error('请先填写物料的数量')
        return
      }

      let orderMaterials = filterData.map(value => {
        return Object.assign({}, value, {
          sourceOrderId: emsOrder.orderId,
          sourceOrderMaterialId: value.orderMaterialId,
          number: value.normalNumber,
          extraNumber: value.extraNumber,
        })
      })

      let orderBean = {
        orderId: '',
        sourceOrderId: emsOrder.orderId,
        orderParentId: '',
        orderPids: '',
        orderNumber: '',
        orderType: this.$businessEnum.ORDER_TYPE_ENUM.outOrder.id,
        orgId: '',
        targetOrgId: '',
        isOverseasStore: '',
        countryCode: '',
        file: '',
        remark: '',
        executeStatus: '',
        executeProgress: '',
        issueTime: '',
        estimateCompletionTime: '',
        receiveTime: '',
        status: '',
        createTime: '',
        createUser: '',
        updateTime: '',
        updateUser: '',
        orderMaterials: orderMaterials,
      }
      addOutOrderForProductionOrder(orderBean).then(res => {
        if (res.success) {
          this.$message.info('出库成功')
          this.handleCancel()
        } else {
          this.$message.error('出库失败：' + res.message)
        }
      })
    },
    handleCancel() {
      this.visible = false
    },
    onEmsMaterialIndex1Selected(materialRow) {
      let {materialId, materialName, materialCode, materialType, costPrice} = materialRow
      // 需要调用接口往订单中添加物料
      let _emsOrder = Object.assign({}, this.emsOrder)
      _emsOrder.orderMaterials = []
      let orderMaterial = {
        orderMaterialId: '',
        orderId: _emsOrder.orderId,
        bomId: '0',  // 单独选择原料时没有BOMID
        materialId: materialId,
        number: 1,
        completedNumber: 0,
        executeStatus: '0',
        executeProgress: '0',
        status: '0',
        createTime: '',
        createUser: '',
        updateTime: '',
        updateUser: '',
      }
      _emsOrder.orderMaterials.push(orderMaterial)
      add(orderMaterial).then(res => {
        if (res.success) {
          this.$message.success('新增成功')
          // this.handleCancel()
          // this.$emit('ok', values)
          this.$refs.table.refresh()
        } else {
          this.$message.info('新增失败：' + res.message)
        }
      })
      // 然后刷新table控件
    }
  }
}
</script>

<style lang="less">
.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
}
</style>
